﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using stwh_Model;
using stwh_BLL;
using stwh_Common;
using Newtonsoft.Json;
using System.Text;
using stwh_Web.Handler.stwh_admin;
using stwh_Common.DEncrypt;
using stwh_Common.HttpProc;
using stwh_Web.Handler.wechat.shop;

namespace stwh_Web.Handler.stwh_web
{
    /// <summary>
    /// honor 的摘要说明
    /// </summary>
    public class honor : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (context.Request.HttpMethod.ToLower() == "post")
                {
                    string type = context.Request["type"];
                    if (type == "1")//留言
                    {
                        context.Response.ContentType = "text/plain";
                        #region 留言
                        string lmnc = context.Request["lmnc"];
                        string lmname = context.Request["lmname"];
                        string lmage = context.Request["lmage"];
                        if (string.IsNullOrEmpty(lmage)) lmage = "0";
                        string lmsex = context.Request["lmsex"];
                        if (string.IsNullOrEmpty(lmsex)) lmsex = "0";
                        string lmsj = context.Request["lmsj"];
                        string lmemail = context.Request["lmemail"];
                        if (!string.IsNullOrEmpty(lmemail))
                        {
                            if (!PageValidate.IsEmail(lmemail))
                            {
                                context.Response.Write("邮箱格式错误！");
                                return;
                            }
                        }
                        string lmsubject = context.Request["lmsubject"];
                        string lmlynr = context.Request["lmlynr"];
                        if (lmlynr.Length > 200)
                        {
                            context.Response.Write("留言内容超出指定字符，请缩减至50字以内！");
                            return;
                        }
                        stwh_leaveMSG model = new stwh_leaveMSG();
                        model.stwh_lmnc = context.Server.HtmlEncode(lmnc);
                        model.stwh_lmname = context.Server.HtmlEncode(lmname);
                        model.stwh_lmage = int.Parse(lmage);
                        model.stwh_lmsex = int.Parse(lmsex);
                        model.stwh_lmsj = context.Server.HtmlEncode(lmsj);
                        model.stwh_lmemail = lmemail;
                        model.stwh_lmsubject = context.Server.HtmlEncode(lmsubject);
                        model.stwh_lmlynr = context.Server.HtmlEncode(lmlynr);
                        model.stwh_lmaddtime = DateTime.Now;
                        model.stwh_lmissh = 0;
                        if (new stwh_leaveMSGBLL().Add(model) > 0) context.Response.Write("留言成功！");
                        else context.Response.Write("留言失败！");
                        #endregion
                    }
                    else if (type=="2") //搜索文章
                    {
                        context.Response.ContentType = "application/json";
                        #region 搜索文章
                        string key = context.Request["key"];
                        if (!string.IsNullOrEmpty(key)&&PageValidate.IsHasCHZNNum(key))
                        {
                            int ss = 0, cc = 0;
                            List<stwh_article> ListData = new stwh_articleBLL().GetListByPage<stwh_article>("stwh_atiszhiding desc,stwh_atorder desc,stwh_atid", "desc", "stwh_atissh = 1 and ("+string.Format("stwh_attitle like '%{0}%' or stwh_atbiaoqian like '%{1}%'", key, key)+")", 0, 15, ref ss, ref cc, 0);
                            string listjson = JsonConvert.SerializeObject(ListData);
                            context.Response.Write(listjson);
                        }
                        #endregion
                    }
                    else if (type == "3")//搜索商品
                    {
                        context.Response.ContentType = "application/json";
                        #region 搜索商品
                        string key = context.Request["key"];
                        if (!string.IsNullOrEmpty(key) && PageValidate.IsHasCHZNNum(key))
                        {
                            int ss = 0, cc = 0;
                            List<stwh_article> ListData = new stwh_articleBLL().GetListByPage<stwh_article>("stwh_piszhiding desc,stwh_porder desc,stwh_pid", "desc", "stwh_pissh = 1 and (" + string.Format("stwh_ptitlesimple like '%{0}%' or stwh_ptitle like '%{1}%' or stwh_pdescription like '%{2}%' or stwh_pbiaoqian like '%{3}%'", key, key,key,key) + ")", 0, 15, ref ss, ref cc, 0);
                            string listjson = JsonConvert.SerializeObject(ListData);
                            context.Response.Write(listjson);
                        }
                        #endregion
                    }
                    else if (type == "4") //获取分页文章内容
                    {
                        #region 分页文章内容
                        string page = context.Request["page"];
                        string pagecount = context.Request["pagecount"];
                        string showtype = context.Request["showtype"];
                        if (!PageValidate.IsNumber(page) || !PageValidate.IsNumber(pagecount) || !PageValidate.IsHasCHZNNum(showtype)) BaseHandler.SendResponseMsgs(context, "-1", "参数错误！", 0);
                        else
                        {
                            string whereStr = "stwh_atissh = 1";
                            List<stwh_artype> AllLisTypetData = new List<stwh_artype>();
                            StringBuilder sb = new StringBuilder();
                            string id = "";
                            switch (showtype.Trim().ToLower())
                            {
                                case "news":
                                    AllLisTypetData = new stwh_artypeBLL().GetModelList("stwh_artid not in (2,3)");
                                    stwh_Web.Handler.stwh_admin.BaseHandler.ArticleList(AllLisTypetData, sb, 1, 0);
                                    id = "1," + sb.ToString() + "0";
                                    break;
                                case "product":
                                    AllLisTypetData = new stwh_artypeBLL().GetModelList("stwh_artid not in (1,3)");
                                    stwh_Web.Handler.stwh_admin.BaseHandler.ArticleList(AllLisTypetData, sb, 2, 0);
                                    id = "2," + sb.ToString() + "0";
                                    break;
                                case "project":
                                    AllLisTypetData = new stwh_artypeBLL().GetModelList("stwh_artid not in (1,2)");
                                    stwh_Web.Handler.stwh_admin.BaseHandler.ArticleList(AllLisTypetData, sb, 3, 0);
                                    id = "3," + sb.ToString() + "0";
                                    break;
                                default:
                                    List<stwh_artype> idlist = new stwh_artypeBLL().GetModelList(string.Format("stwh_artname like '%{0}%'", showtype.ToLower().Trim()));
                                    if (idlist.Count > 0)
                                    {
                                        AllLisTypetData = new stwh_artypeBLL().GetModelList("1=1");
                                        //查询当前栏目下的子栏目id
                                        stwh_Web.Handler.stwh_admin.BaseHandler.ArticleList(AllLisTypetData, sb, idlist[0].stwh_artid, 0);
                                        id = idlist[0].stwh_artid + "," + sb.ToString() + "0";
                                    }
                                    break;
                            }
                            if (!string.IsNullOrEmpty(id)) whereStr = whereStr + " and stwh_artid in (" + id + ")";
                            int ss = 0, cc = 0;
                            List<stwh_article> ListData = new stwh_articleBLL().GetListByPage<stwh_article>("stwh_atiszhiding desc,stwh_atorder desc,stwh_atid", "desc", whereStr, int.Parse(pagecount), int.Parse(page), ref ss, ref cc, 0);
                            BaseHandler.SendResponseMsgs(context, "0", ListData, cc);
                        }
                        #endregion
                    }
                    else if (type == "5")//发送短信验证码（使用253短信平台）
                    {
                        #region send短信验证码
                        string pSessionID = context.Session.SessionID;
                        string phone = context.Request["phone"];
                        if (!PageValidate.IsMobileNumber(phone)) BaseHandler.SendResponseMsgs(context, "-1", "手机号码格式错误！", 0);
                        else
                        {
                            #region 判断用户是否发送验证码
                            bool IsSend = true;
                            //判断用户是否发送验证码
                            if (context.Session["sendcode"] == null) context.Session["sendcode"] = new Dictionary<string, DateTime>();
                            Dictionary<string, DateTime> Log = (Dictionary<string, DateTime>)context.Session["sendcode"];
                            int ss = 0;
                            if (Log.ContainsKey(pSessionID))
                            {
                                DateTime LastTime = Log[pSessionID];
                                TimeSpan tp = DateTime.Now - LastTime;
                                //防止用户快速刷新页面不断发送验证码，60秒后才能再一次发送验证码
                                if (tp.TotalSeconds <= 60)
                                {
                                    IsSend = false;
                                    ss = tp.Seconds;
                                }
                            }
                            #endregion
                            if (IsSend)
                            {
                                string PostUrl = ConfigHelper.GetConfigString("WebReference.Service.PostUrl");
                                string user = ConfigHelper.GetConfigString("WebReference.Service.PostUrl.user");
                                string pwd = DESEncrypt.Decrypt(ConfigHelper.GetConfigString("WebReference.Service.PostUrl.pwd"));
                                #region 随机生成验证码
                                string code = "";
                                Random rand = new Random();
                                //定义随机字符串
                                string letter = "012345678901234567890123456789";
                                //生成验证码
                                for (int i = 0; i < 5; i++)
                                {
                                    code += letter.Substring(rand.Next(0, letter.Length - 1), 1);
                                }
                                #endregion
                                string msgcontent = string.Format("【毕上生物科技】注册短信验证码为：{0}，如果没有提交请求请忽略。", code);
                                string postdata = string.Format("un={0}&pw={1}&phone={2}&msg={3}&rd=0", user, pwd, phone, msgcontent);
                                try
                                {
                                    WebClient wc = new WebClient();
                                    wc.Encoding = Encoding.UTF8;
                                    wc.Post(PostUrl, postdata);
                                    if (Log.ContainsKey(pSessionID)) Log[pSessionID] = DateTime.Now;
                                    else Log.Add(pSessionID, DateTime.Now);
                                    Dictionary<string, string> codephone = new Dictionary<string, string>();
                                    codephone.Add(phone, code);
                                    context.Session["regcode"] = codephone;
                                    BaseHandler.SendResponseMsgs(context, "0", "发送验证码成功！", 0);
                                }
                                catch (Exception)
                                {
                                    BaseHandler.SendResponseMsgs(context, "-1", "发送验证码失败！", 0);
                                }
                            }
                            else BaseHandler.SendResponseMsgs(context, "-2", ss, 0);
                        }
                        #endregion
                    }
                    else if (type == "6")//发送找回密码验证码（使用253短信平台）
                    {
                        #region send短信验证码
                        string pSessionID = context.Session.SessionID;
                        string phone = context.Request["phone"];
                        if (!PageValidate.IsMobileNumber(phone)) BaseHandler.SendResponseMsgs(context, "-1", "手机号码格式错误！", 0);
                        else
                        {
                            List<stwh_buyuser> chkmodel = new stwh_buyuserBLL().GetModelList("stwh_bumobile = " + phone);
                            if (chkmodel.Count == 0) BaseHandler.SendResponseMsgs(context, "-1", "手机号码不存在！", 0);
                            else
                            {
                                #region 判断用户是否发送验证码
                                bool IsSend = true;
                                //判断用户是否发送验证码
                                if (context.Session["sendcode"] == null) context.Session["sendcode"] = new Dictionary<string, DateTime>();
                                Dictionary<string, DateTime> Log = (Dictionary<string, DateTime>)context.Session["sendcode"];
                                int ss = 0;
                                if (Log.ContainsKey(pSessionID))
                                {
                                    DateTime LastTime = Log[pSessionID];
                                    TimeSpan tp = DateTime.Now - LastTime;
                                    //防止用户快速刷新页面不断发送验证码，60秒后才能再一次发送验证码
                                    if (tp.TotalSeconds <= 60)
                                    {
                                        IsSend = false;
                                        ss = tp.Seconds;
                                    }
                                }
                                #endregion
                                if (IsSend)
                                {
                                    string PostUrl = ConfigHelper.GetConfigString("WebReference.Service.PostUrl");
                                    string user = ConfigHelper.GetConfigString("WebReference.Service.PostUrl.user");
                                    string pwd = DESEncrypt.Decrypt(ConfigHelper.GetConfigString("WebReference.Service.PostUrl.pwd"));
                                    #region 随机生成验证码
                                    string code = "";
                                    Random rand = new Random();
                                    //定义随机字符串
                                    string letter = "012345678901234567890123456789";
                                    //生成验证码
                                    for (int i = 0; i < 5; i++)
                                    {
                                        code += letter.Substring(rand.Next(0, letter.Length - 1), 1);
                                    }
                                    #endregion
                                    string msgcontent = string.Format("【毕上生物科技】正在操作找回密码，短信验证码为：{0}，如果没有提交请求请忽略。", code);
                                    string postdata = string.Format("un={0}&pw={1}&phone={2}&msg={3}&rd=0", user, pwd, phone, msgcontent);
                                    try
                                    {
                                        WebClient wc = new WebClient();
                                        wc.Encoding = Encoding.UTF8;
                                        wc.Post(PostUrl, postdata);
                                        if (Log.ContainsKey(pSessionID)) Log[pSessionID] = DateTime.Now;
                                        else Log.Add(pSessionID, DateTime.Now);
                                        Dictionary<string, string> codephone = new Dictionary<string, string>();
                                        codephone.Add(phone, code);
                                        context.Session["upwdcode"] = codephone;//找回密码
                                        BaseHandler.SendResponseMsgs(context, "0", "发送验证码成功！", 0);
                                    }
                                    catch (Exception)
                                    {
                                        BaseHandler.SendResponseMsgs(context, "-1", "发送验证码失败！", 0);
                                    }
                                }
                                else BaseHandler.SendResponseMsgs(context, "-2", ss, 0);
                            }
                        }
                        #endregion
                    }
                    else if (type == "7")//更换手机验证码（使用253短信平台）
                    {
                        #region send短信验证码
                        string pSessionID = context.Session.SessionID;
                        string phone = context.Request["phone"];
                        if (!PageValidate.IsMobileNumber(phone)) BaseHandler.SendResponseMsgs(context, "-1", "手机号码格式错误！", 0);
                        else
                        {
                            stwh_buyuser model = new stwh_buyuser();
                            if (ShopCommon.ChkShopLoginUser(context, ref model))
                            {
                                if (string.Compare(model.stwh_bumobile, phone) != 0)
                                {
                                    #region 判断用户是否发送验证码
                                    bool IsSend = true;
                                    //判断用户是否发送验证码
                                    if (context.Session["sendcode"] == null) context.Session["sendcode"] = new Dictionary<string, DateTime>();
                                    Dictionary<string, DateTime> Log = (Dictionary<string, DateTime>)context.Session["sendcode"];
                                    int ss = 0;
                                    if (Log.ContainsKey(pSessionID))
                                    {
                                        DateTime LastTime = Log[pSessionID];
                                        TimeSpan tp = DateTime.Now - LastTime;
                                        //防止用户快速刷新页面不断发送验证码，60秒后才能再一次发送验证码
                                        if (tp.TotalSeconds <= 60)
                                        {
                                            IsSend = false;
                                            ss = tp.Seconds;
                                        }
                                    }
                                    #endregion
                                    if (IsSend)
                                    {
                                        string PostUrl = ConfigHelper.GetConfigString("WebReference.Service.PostUrl");
                                        string user = ConfigHelper.GetConfigString("WebReference.Service.PostUrl.user");
                                        string pwd = DESEncrypt.Decrypt(ConfigHelper.GetConfigString("WebReference.Service.PostUrl.pwd"));
                                        #region 随机生成验证码
                                        string code = "";
                                        Random rand = new Random();
                                        //定义随机字符串
                                        string letter = "012345678901234567890123456789";
                                        //生成验证码
                                        for (int i = 0; i < 5; i++)
                                        {
                                            code += letter.Substring(rand.Next(0, letter.Length - 1), 1);
                                        }
                                        #endregion
                                        string msgcontent = string.Format("【毕上生物科技】您正在操作更换手机号码，短信验证码为：{0}，如果没有提交请求请忽略。", code);
                                        string postdata = string.Format("un={0}&pw={1}&phone={2}&msg={3}&rd=0", user, pwd, phone, msgcontent);
                                        try
                                        {
                                            WebClient wc = new WebClient();
                                            wc.Encoding = Encoding.UTF8;
                                            wc.Post(PostUrl, postdata);
                                            if (Log.ContainsKey(pSessionID)) Log[pSessionID] = DateTime.Now;
                                            else Log.Add(pSessionID, DateTime.Now);
                                            Dictionary<string, string> codephone = new Dictionary<string, string>();
                                            codephone.Add(phone, code);
                                            context.Session["newcode"] = codephone;
                                            BaseHandler.SendResponseMsgs(context, "0", "发送验证码成功！", 0);
                                        }
                                        catch (Exception)
                                        {
                                            BaseHandler.SendResponseMsgs(context, "-1", "发送验证码失败！", 0);
                                        }
                                    }
                                    else BaseHandler.SendResponseMsgs(context, "-2", ss, 0);
                                }
                                else BaseHandler.SendResponseMsgs(context, "-1", "新手机号码不能与旧手机号码相同！", 0);
                            }
                            else BaseHandler.SendResponseMsgs(context, "-1", "登录状态已失效，请重新登录！", 0);
                        }
                        #endregion
                    }
                    else
                        context.Response.Write("类型错误！");
                }
                else context.Response.Write("数据传输方法错误，请采用post方式！");
            }
            catch (Exception)
            {

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}